<?php
declare (strict_types=1);

namespace app\admin\controller;

use thans\jwt\facade\JWTAuth;
use think\Exception;
use think\response\Json;

class Index extends Base
{
    /**
     * 登录
     */
    public function login(): Json
    {
        // 用户名
        $username = request()->post('username');
        // // 密码
        $password = request()->post('password');

        // 登录
        try {
            if (empty($username)) {
                throw new Exception("用户名不能为空");
            }

            if (empty($password)) {
                throw new Exception("密码不能为空");
            }

            // 判断用户登录
            $user = $this->getAdminService()->login($username, $password);
            $jwtData = [
                'id' => $user->getId(),
                'time' => time(),
                'username' => $user->getUsername(),
            ];
            $token = JWTAuth::builder($jwtData);

            $returnArr = [
                'token' => "bearer " . $token,
                'user' => [
                    'id' => $user->getId(),
                    'username' => $user->getUsername(),
                ]
            ];
            return $this->requestSuccessReturn($returnArr);

        } catch (Exception $e) {
            $data = $e->getData();
            $message = $e->getMessage();
            if(!empty($data['error']) && !empty($data['error']['data'])){
                $message = $data['error']['data'];
            }
            return $this->requestFailReturn($message, $e->getCode());
        }
    }

    /**
     * 获取所有的领域
     */
    public function get_territory(): Json{
        $territory = config('ext.territory');
        return $this->requestSuccessReturn($territory);
    }

    //获取系统配置
    public function get_system_config(): Json
    {
        $name = request()->get('name');
        $config = config($name);
        return $this->requestSuccessReturn($config);
    }
}
